﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Security.Cryptography;
using System.Runtime.Serialization;

namespace RoketPack.Management
{
    /// <summary>
    /// This class represents a remote repository, which stores information about
    /// available applications, components and their updates.
    /// </summary>
    public class Repository : MarshalByRefObject, ISerializable
    {
        private string p_Url;
        private string p_Name = null;
        private string p_Description = null;
        private Dictionary<string, Application> p_Applications = null;

        public Repository(string url)
        {
            this.p_Url = url.TrimEnd('/');
        }

        public Repository(string url, string name)
        {
            this.p_Url = url.TrimEnd('/');
            this.p_Name = name;
        }

        public Repository(string url, string name, string description)
        {
            this.p_Url = url.TrimEnd('/');
            this.p_Name = name;
            this.p_Description = description;
        }

        internal void Initalize()
        {
            try
            {
                byte[] data = Downloader.Grab(this.p_Url + "/software.xml");

                ConfigurationReader config = new ConfigurationReader();
                this.p_Applications = config.GetApplicationList(data, this);
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.SecureChannelFailure)
                {
                    // Unable to establish a secure connection.
                    throw new CryptographicException("A secure connection could not be made to the target repository.");
                }
                else
                    throw;
            }
        }

        public string Url
        {
            get
            {
                return this.p_Url.TrimEnd('/');
            }
        }

        public string Name
        {
            get
            {
                return this.p_Name;
            }
        }

        public string Description
        {
            get
            {
                return this.p_Description;
            }
        }

        internal Dictionary<string, Application> Applications
        {
            get
            {
                return this.p_Applications;
            }
        }

        public override object InitializeLifetimeService()
        {
            return null;
        }

        #region ISerializable Members

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
